import { defineStore } from 'pinia'
import { ref } from 'vue'
import { authApi, type LoginRequest } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const isLoggedIn = ref(false)
  const accessToken = ref('')
  const refreshToken = ref('')
  // 为避免推断为 never/null，明确为 any，后续可替换为具体 User 类型
  const user = ref<any>(null)

  // 初始化认证状态
  const initAuth = () => {
    const token = localStorage.getItem('access_token')
    const refresh = localStorage.getItem('refresh_token')
    const userStr = localStorage.getItem('user')
    
    console.log('🔄 初始化认证状态')
    console.log('🔑 Token存在:', !!token)
    console.log('🔄 Refresh存在:', !!refresh)
    console.log('👤 用户数据存在:', !!userStr)
    
    if (token && refresh && userStr) {
      try {
        const userData = JSON.parse(userStr)
        // 验证用户数据完整性
        if (userData && userData.id && userData.username) {
          accessToken.value = token
          refreshToken.value = refresh
          user.value = userData
          isLoggedIn.value = true
          console.log('✅ 认证状态初始化完成，已登录:', userData.username)
          return true
        } else {
          console.warn('⚠️ 用户数据不完整，清除认证信息')
          clearAuth()
        }
      } catch (error) {
        console.error('❌ 解析用户数据失败:', error)
        clearAuth()
      }
    } else {
      console.log('⚠️ 认证信息不完整，未登录状态')
      clearAuth()
    }
    return false
  }

  // 清除认证信息的内部方法
  const clearAuth = () => {
    accessToken.value = ''
    refreshToken.value = ''
    isLoggedIn.value = false
    user.value = null
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('user')
  }

  // 登录
  const login = async (credentials: LoginRequest) => {
    try {
      const response = await authApi.login(credentials)
      
      accessToken.value = response.accessToken
      refreshToken.value = response.refreshToken
      isLoggedIn.value = true
      
      // 保存token到localStorage
      localStorage.setItem('access_token', response.accessToken)
      localStorage.setItem('refresh_token', response.refreshToken)
      
      // 获取用户信息
      try {
        const userInfo = await authApi.me()
        user.value = userInfo
        localStorage.setItem('user', JSON.stringify(userInfo))
        console.log('✅ 登录成功，用户信息:', userInfo)
      } catch (userError) {
        console.error('⚠️ 获取用户信息失败:', userError)
        // 即使获取用户信息失败，登录仍然成功
      }
      
      return true
    } catch (error) {
      console.error('❌ 登录失败:', error)
      clearAuth()
      return false
    }
  }

  // 登出
  const logout = () => {
    console.log('🚪 用户登出')
    clearAuth()
  }

  // 刷新token
  const refreshAuth = async () => {
    try {
      const response = await authApi.refresh({ refreshToken: refreshToken.value })
      accessToken.value = response.accessToken
      localStorage.setItem('access_token', response.accessToken)
      return true
    } catch (error) {
      console.error('Refresh token failed:', error)
      logout()
      return false
    }
  }

  // 设置token（用于注册后自动登录）
  const setTokens = (access: string, refresh: string) => {
    accessToken.value = access
    refreshToken.value = refresh
    isLoggedIn.value = true
    
    localStorage.setItem('access_token', access)
    localStorage.setItem('refresh_token', refresh)
  }

  return {
    isLoggedIn,
    accessToken,
    refreshToken,
    user,
    initAuth,
    login,
    logout,
    refreshAuth,
    setTokens
  }
})